package hn.cch.spring_async_call.service;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


/**
 * 业务：延时
 */
@Service
public class ApiService {

    private Logger logger = LoggerFactory.getLogger(ApiService.class);


    public void sync() {
        logger.info("sync void start");
        try {
            Thread.sleep(1 * 1000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }
        logger.info("sync void stop");
    }

    public Future<String> sync(String param) {
        logger.info("sync param start");
        Future<String> future = Executors.newSingleThreadExecutor().submit(() -> {
            logger.info("submit");
            try {
                Thread.sleep(10 * 1000);
            } catch (InterruptedException e) {
                logger.error(e.getMessage());
            }
            logger.info("return");
            return param;
        });

        logger.info("sync param stop");
        return future;
    }


    @Async
    public void async() {
        logger.info("async void start");
        try {
            Thread.sleep(10 * 1000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }
        logger.info("async void stop");
    }

    @Async
    public Future<String> async(String param) {
        logger.info("async param start");
        try {
            Thread.sleep(10 * 1000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }
        Future<String> future = new AsyncResult<String>(param);
        logger.info("async param stop");
        return future;
    }


    @Async
    public Future<String> async(String param, CountDownLatch countDownLatch) {
        logger.info("async param start");
        Future<String> future = null;
        try {
            Thread.sleep(10 * 1000);
            future = new AsyncResult<String>(param);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
            future = new AsyncResult<String>(e.getMessage());
        }
        logger.info("async param stop");
        countDownLatch.countDown();
        return future;
    }

}
